/*
 * @Author: jinye.zhang
 * @Version: 1.0.0
 * @LastEditors: jinye.zhang
 * @Description: new file
 */
import Vue from "vue";
// 授权登录
import { login } from "@/api/user.js";
// 登录授权 source_code 上级邀请码
export function authorization({ source_code, code, resetToken = false }) {
  return new Promise((resolve, reject) => {
    const that = this;
    // 获取账户信息
    let appId = ""; // 如果是不支持自动获取的应用请手动填写上appi，否则整个应用无法访问
    // #ifdef MP-QQ || MP-WEIXIN || MP-KUAISHOU
    appId = uni.getAccountInfoSync().miniProgram.appId;
    // #endif

    // #ifdef MP-TOUTIAO
    appId = uni.getEnvInfoSync().microapp.appId;
    // #endif

    // #ifdef MP-WEIXIN
    // return;
    uni.login({
      provider: "wx",
      success: function(loginRes) {
        login({
          code: loginRes.code,
          appId: appId,
          source_code,
          source: uni.getStorageSync("source"),
        }).then(async (result) => {
          console.log("login>>>>", result);
          if (result && result.code === 200) {
            if (result.data && result.data.status === "invalid") {
              await Vue.prototype.$store.dispatch("setToken", "");
              uni.showModal({
                title: "温馨提示",
                content: "平台账号违规已暂停使用，如有疑问，请联系平台客服。",
                showCancel: false,
                success: ({ confirm, cancel }) => {
                  uni.exitMiniProgram();
                },
              });
            } else if (!result.data.status || result.data.status != "invalid") {
              const userInfo = result.data.userInfo;
              uni.setStorageSync("token", result.data.token);
              await Vue.prototype.$store.dispatch(
                "setToken",
                result.data.token
              );
              await Vue.prototype.$store.dispatch(
                "setUserInfo",
                result.data.userInfo
              );
              await Vue.prototype.$store.dispatch(
                "setAppletInfo",
                result.data.appletInfo
              );
              await Vue.prototype.$store.dispatch(
                "setCheckVersion",
                result.data.appletVersion
              );
              console.log("userInfo>>", userInfo);
              // 如果存在用户的头像和名称，则表示已经授权登录过
              if (userInfo.merchant_id && userInfo.merchant_id != "") {
                await Vue.prototype.$store.dispatch("setIsLogin", true);
              } else {
                uni.reLaunch({
                  url: "/pages/merchant/merchant",
                });
              }

              // 如果还不是创作者，则前往注册创作者
              // if (!userInfo.merchant_id||userInfo.merchant_id=='') {
              //   uni.reLaunch({
              //     url: "/pages/merchant/merchant",
              //   });
              // }

              resolve(result);
            }
          } else {
            reject(result);
          }
        });
      },
    });
    // #endif

    // #ifdef H5
    const isWeChatFlag = isWeChat();

    login({
      code,
      appId: "",
      source_code,
      isWeChatFlag,
      resetToken,
    }).then(async (result) => {
      if (result && result.data) {
        const data = result.data;
        if (data.authUrl) {
          const businessId = uni.getStorageSync("businessId");
          location.href = data.authUrl;
        } else {
          if (result.data && result.data.status === "invalid") {
            await Vue.prototype.$store.dispatch("setToken", "");
            uni.showModal({
              title: "温馨提示",
              content: "平台账号违规已暂停使用，如有疑问，请联系平台客服。",
              showCancel: false,
              success: ({ confirm, cancel }) => {
                uni.exitMiniProgram();
              },
            });
          } else {
            const userInfo = result.data.userInfo;
            uni.setStorageSync("token", result.data.token);
            await Vue.prototype.$store.dispatch("setToken", result.data.token);
            await Vue.prototype.$store.dispatch(
              "setUserInfo",
              result.data.userInfo
            );
            await Vue.prototype.$store.dispatch(
              "setAppletInfo",
              result.data.appletInfo
            );
            await Vue.prototype.$store.dispatch(
              "setCheckVersion",
              result.data.appletVersion
            );
            // 如果存在用户的头像和名称，则表示已经授权登录过
            if (userInfo.merchant_id && userInfo.merchant_id!='') {
              await Vue.prototype.$store.dispatch("setIsLogin", true);
            }else{
              uni.reLaunch({
                url: "/pages/merchant/merchant",
              });
            }
            resolve(result);
          }
        }
      } else {
        reject(result);
      }
    });
    // #endif
  });
}

// 判断是否为微信环境
function isWeChat() {
  let ua = window.navigator.userAgent.toLowerCase();
  return ua.match(/MicroMessenger/i) == "micromessenger"; // 判定为true则是微信浏览器，false则不是
}
